import 'package:fluent_ui/fluent_ui.dart';
import 'package:flutter/material.dart' show DataCell, DataColumn;
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:provider/provider.dart';

import '../../components/buttons.dart';
import '../../components/data_table.dart';
import '../../model/semester_model.dart';
import '../../utils/date_utils.dart';
import '../app/app_dict_data.dart';
import 'school_semester_view_model.dart';

class SchoolSemesterViewAdd extends StatefulWidget {
  final String schoolId;
  final List<String> checkedSemesters;

  const SchoolSemesterViewAdd({
    super.key,
    required this.schoolId,
    required this.checkedSemesters,
  });

  @override
  State<SchoolSemesterViewAdd> createState() => _SchoolSemesterViewAddState();
}

class _SchoolSemesterViewAddState extends State<SchoolSemesterViewAdd> {
  final queryFormKey = GlobalKey<FormState>();
  final tableKey = GlobalKey<DataTableState<SemesterItemRes>>();

  @override
  void initState() {
    super.initState();
    //加载数据
    final model = context.read<SchoolSemesterViewModel>();
    model.loadInit(afterHandler: () => query(model));
  }

  void query(final SchoolSemesterViewModel model) => model.querySemesters();

  Widget buildQueryForm(final SchoolSemesterViewModel model) {
    Widget buildField(SemesterQueryField field,
        Widget Function(TextEditingController? c, String label) handler) {
      final label = field.label;
      final controller = model.getController(field);
      final child = handler.call(controller, label);
      return SizedBox(
        width: 128.w,
        child: InfoLabel(label: label, child: child),
      );
    }

    return Form(
      key: queryFormKey,
      child: Wrap(
        spacing: 5.w,
        children: [
          //标题
          buildField(
            SemesterQueryField.title,
            (c, label) => TextFormBox(controller: c, placeholder: label),
          ),
          //状态
          buildField(
            SemesterQueryField.status,
            (c, label) => ComboboxFormField(
              placeholder: Text(label),
              items: model.statusOpts,
              onChanged: (val) => c?.text = val ?? '1',
            ),
          ),
        ],
      ),
    );
  }

  Widget buildQueryBars(final SchoolSemesterViewModel model) => Wrap(
        spacing: 2.w,
        children: [
          //查询
          buttons.query(onPressed: () => model.querySemesters()),
          //重置
          buttons.reset(onPressed: () {
            queryFormKey.currentState?.reset();
            model.cleanSemesterFields();
            model.querySemesters();
          }),
        ],
      );

  @override
  Widget build(final BuildContext context) => Consumer<SchoolSemesterViewModel>(
        builder: (context, model, _) => ScaffoldPage.scrollable(
          header: Column(children: [
            Padding(
              padding: () {
                final padding = PageHeader.horizontalPadding(context);
                return EdgeInsetsDirectional.symmetric(horizontal: padding);
              }(),
              child: Row(children: [
                //查询条件
                buildQueryForm(model),
                //占位
                Expanded(child: Container()),
                //查询按钮
                buildQueryBars(model),
              ]),
            ),
            SizedBox(height: 15.h),
          ]),
          children: [
            //数据列表
            buildTable(model),
          ],
        ),
      );

  Widget buildTable(final SchoolSemesterViewModel model) {
    final labels = <String>['编码', '名称', '开始日期', '结束日期', '状态', "操作"];
    DataCell buildCell(String? Function() handler) => DataCell(Text(
          handler.call() ?? '',
          softWrap: false,
          overflow: TextOverflow.ellipsis,
        ));
    return DataTable<SemesterItemRes>(
      key: tableKey,
      model: model.querySemesterModel,
      columns: [...labels.map((label) => DataColumn(label: Text(label)))],
      onLoadData: () => model.querySemesters(),
      onRowCallback: (row) => [
        //编码
        buildCell(() => row.code),
        //名称
        buildCell(() => row.title),
        //开始日期
        buildCell(() => dateUtils.format('yyyy-MM-dd', row.start)),
        //结束日期
        buildCell(() => dateUtils.format('yyyy-MM-dd', row.end)),
        //状态
        buildCell(() => appDictData.getLabel('status', row.status)),
        //操作
        DataCell(() {
          return Checkbox(
            checked: widget.checkedSemesters.contains(row.id),
            onChanged: (v) {
              final semesterId = row.id;
              final checkedSemesters = widget.checkedSemesters;
              if (checkedSemesters.contains(semesterId)) {
                checkedSemesters.remove(semesterId);
              } else {
                checkedSemesters.add(semesterId);
              }
              //触发查询
              model.querySemesters();
            },
          );
        }()),
      ],
    );
  }
}
